package com.dfrz.household.realm;

import com.dfrz.household.bean.Permission;
import com.dfrz.household.bean.User;
import com.dfrz.household.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    IUserService userService;
    /**
     * 授权  （ 通过用户名查询 用户拥有的角色和权限）
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        User u = (User) principalCollection.getPrimaryPrincipal();
        //查询的用户 包含了角色和权限 (这里的用户对象已经包含有数据库查询出来的角色和权限数据)
        User user=userService.queryOneByLoginName(u.getUname());
        // 把角色和权限添加至shiro框架中
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(user.getRole().getRolekey());
        List<Permission> permissions=user.getRole().getPermissions();
        //把权限添加至Shiro中
        for (Permission p:permissions
        ) {
            simpleAuthorizationInfo.addStringPermission(p.getPkey());
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 身份验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if(authenticationToken.getPrincipal()==null){
            return null;
        }
        //身份信息
        String uname=authenticationToken.getPrincipal().toString();
        //通过数据库-查用户
        User user=userService.queryOneByLoginName(uname);
        if(user==null){
            return null;
        }
        else{
            //验证
            ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUname());
            SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(user, user.getUpass(),
                    credentialsSalt, getName());
            return simpleAuthenticationInfo;
        }
    }
}
